package com.gateway.filters;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: TODO
 * @Author: mis_wu
 * @Date: 2022/4/27
 * 网管全局过滤器
 **/
//@Component
public class TokenGlobalFilter implements GlobalFilter, Ordered {

    @Value("${server.port}")
    private String serverPort;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if (StringUtils.isEmpty(token) || token == null){
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            String msg = "token is null";
            DataBuffer wrap = response.bufferFactory().wrap(msg.getBytes());
            //返回给页面 token is null
            return response.writeWith(Mono.just(wrap));
        }
        //在 请求头中存放 serverPort
        ServerHttpRequest request = exchange.getRequest().mutate().header("serverPort", serverPort).build();
        return chain.filter(exchange.mutate().request(request).build());
    }

    /**
     * 优先级 -1为最高
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
